﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using OpenAdmin.Core.DbContextLocators;
using OpenAdmin.Core.Models;
using OpenAdmin.HttpApi.Proxies;
using StackExchange.Profiling;

namespace OpenAdmin.HttpApi.Controllers;

/// <summary>
/// 博客相关
/// </summary>
[ApiController, Route("api/[controller]/[action]"), ApiExplorerSettings(GroupName = "Blog")]
public class BlogController : ControllerBase
{
    private readonly ILogger<BlogController> _logger;
    private readonly IRepository<Blog, BloggingDbContextLocator> _blogRepository;
    private readonly IA _a;
    private readonly IB _b;
    private readonly IHttpContextAccessor _accessor;
    private readonly ITestProxyInterface _testProxyInterface;
    /// <summary>
    /// ctor
    /// </summary>
    /// <param name="logger"></param>
    /// <param name="blogRepository"></param>
    /// <param name="a"></param>
    /// <param name="b"></param>
    /// <param name="accessor"></param>
    /// <param name="testProxyInterface"></param>
    public BlogController(ILogger<BlogController> logger, IRepository<Blog, BloggingDbContextLocator> blogRepository,
        IA a, IB b, IHttpContextAccessor accessor, ITestProxyInterface testProxyInterface)
    {
        _logger = logger;
        _blogRepository = blogRepository;
        _a = a;
        _b = b;
        _accessor = accessor;
        _testProxyInterface = testProxyInterface;
    }
    /// <summary>
    /// 添加博客
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [HttpPost]
    [AllowAnonymous]
    //[ApiExplorerSettings(IgnoreApi = true)]
    public async Task<IActionResult> AddBlogAsync([FromBody] BlogDto dto)
    {
        var blog = new Blog()
        {
            Name = "哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈",//dto.Name,
            Url = dto.Url,
            CreateTime = DateTime.Now,
        };
        var result = _blogRepository.InsertAndCommitEntry(blog).Entity;
        return Ok(await Task.FromResult(result));

        //var row = _blogRepository.SqlNonQuery($"INSERT INTO Blogs(`Name`,Url,CreatedTime) VALUES('{blog.Name}', '{blog.Url}', '{DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss")}')");
        //if (row > 0)
        //{
        //    var blogs = _blogRepository.SqlQuery<Blog>("select * from Blogs order by createdtime desc");

        //    return Ok(blogs);
        //}

        //return BadRequest();
    }
    /// <summary>
    /// 修改博客
    /// </summary>
    /// <param name="blog"></param>
    /// <returns></returns>
    [HttpPut]
    //[ApiExplorerSettings(GroupName = "分组一")]
    public IActionResult UpdateBlog([FromBody] Blog blog)
    {
        var result = _blogRepository.UpdateAndCommitEntry(blog);
        return Ok(result.Entity);
    }
    /// <summary>
    /// 删除博客
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpDelete]
    //[ApiExplorerSettings(GroupName = "分组一")]
    public IActionResult DeleteBlog([FromBody] int id)
    {
        var result = _blogRepository.DeleteAndCommitEntry(new Blog { Id = id });
        return Ok(result.Entity);
    }
    /// <summary>
    /// 获取博客列表
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    //[ApiExplorerSettings(GroupName = "分组一")]
    //[Authorize(Policy = "Test")]
    //[FastAuthorize("Permission")]
    //[UnitOfWork]
    [AllowAnonymous, ProducesResponseType(typeof(List<Blog>), 200), NonNormalize]
    public async Task<IActionResult> Get()
    {
        //return BadRequest("aaa");
        //throw new UserFriendlyException("测试异常", "zx1001");
        //var blogs = _blogRepository.SqlQuery<Blog>("select * from Blogs");

        //var blogs = _blogRepository.Entities.ToList();

        ////var postRepository = _blogRepository.Change<Post>();
        ////var posts = postRepository.Entities.ToList();
        //var postRepository = _blogRepository.Change<Post, BloggingDbContextLocator>();
        //var posts = postRepository.Entities.ToList();

        //var userRepository = _blogRepository.Change<SysUser, ApplicationDbContextLocator>();
        //var users = userRepository.Entities.ToList();

        //_logger.LogInformation(Newtonsoft.Json.JsonConvert.SerializeObject(users));
        //blogs.ForEach(b =>
        //{
        //    b.Posts = posts.Where(p => p.BlogId == b.Id).ToList();
        //});
        //_a.Show();

        //_b.Show();

        //_testProxyInterface.Show();
        return await Task.FromResult(Ok(new List<Blog>() { new Blog { Id = 1 }, new Blog { Id = 2 } }));
    }
    /// <summary>
    /// 统计博客文章
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    //[ApiExplorerSettings(GroupName = "分组一")]
    public IEnumerable<BlogPostsCount> GetBlogPostsCount()
    {
        //return _context.Set<BlogPostsCount>().ToList();
        return new List<BlogPostsCount>();
    }
    /// <summary>
    /// 获取MiniProfiler
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    //[ApiExplorerSettings(GroupName = "分组二")]
    public IActionResult GetMiniProfiler()
    {
        var html = MiniProfiler.Current.RenderIncludes(_accessor.HttpContext);
        return Ok(html.Value);
    }
    /// <summary>
    /// 获取token
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    //[ApiExplorerSettings(GroupName = "分组三")]
    public IActionResult Token()
    {
        var claimsIdentity = new ClaimsIdentity(new[] {
            new Claim(ClaimTypes.Name,"aaa")
        });
        //var handle = new JwtSecurityTokenHandler();
        //var tokenDescriptor = new SecurityTokenDescriptor
        //{
        //    Subject = claimsIdentity,
        //    Expires = DateTime.Now.AddMinutes(3),
        //    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes("ijurkbdlhmklqacwqzdxmkkhvqowlyqa")), SecurityAlgorithms.HmacSha256)
        //};
        //var securityToken = handle.CreateToken(tokenDescriptor);
        //var token = handle.WriteToken(securityToken);

        //var token = JwtEncryption.Encrypt(null);

        HttpContext.SignInAsync(JwtBearerDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));

        return Ok("");
    }
}
/// <summary>
/// 
/// </summary>
public class TestDto
{
    /// <summary>
    /// 
    /// </summary>
    [Required(ErrorMessage = "名称不能为空")]
    public string Name { get; set; }
}
